<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>社交中心</span>
          <div>
            <el-button type="primary" @click="openAddFriendDialog">添加好友</el-button>
            <el-button type="info" @click="openFriendRequests">
              好友请求
              <el-badge v-if="requestCount > 0" :value="requestCount" class="item" />
            </el-button>
          </div>
        </div>
      </template>

      <div class="social-container">
        <!-- 好友列表侧边栏 -->
        <div class="friends-sidebar">
          <el-input
            v-model="searchText"
            placeholder="搜索好友..."
            prefix-icon="Search"
            clearable
            class="search-input"
          />

          <div class="friend-list">
            <div
              v-for="friend in filteredFriends"
              :key="friend.id"
              class="friend-item"
              :class="{ active: currentFriend?.id === friend.id }"
              @click="selectFriend(friend)"
            >
              <div class="friend-avatar">
                <el-avatar :size="40" :src="friend.avatar">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                </el-avatar>
                <div
                  :class="['status-dot', friend.status]"
                  :title="
                    friend.status === 'online'
                      ? '在线'
                      : friend.status === 'offline'
                        ? '离线'
                        : '忙碌'
                  "
                ></div>
              </div>
              <div class="friend-info">
                <div class="friend-name">{{ friend.nickname || friend.username }}</div>
                <div class="last-message">{{ getLastMessage(friend) }}</div>
              </div>
              <div class="friend-meta">
                <div class="message-time">{{ getLastMessageTime(friend) }}</div>
                <el-badge
                  v-if="friend.unreadCount > 0"
                  :value="friend.unreadCount"
                  class="unread-badge"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 聊天内容区 -->
        <div class="chat-content">
          <div v-if="!currentFriend" class="empty-chat">
            <el-empty description="选择一位好友开始聊天" />
          </div>

          <template v-else>
            <!-- 聊天头部信息 -->
            <div class="chat-header">
              <div class="friend-info">
                <span class="friend-name">
                  {{ currentFriend.nickname || currentFriend.username }}
                </span>
                <span class="friend-status">
                  {{
                    currentFriend.status === "online"
                      ? "在线"
                      : currentFriend.status === "offline"
                        ? "离线"
                        : "忙碌"
                  }}
                </span>
              </div>
              <div class="header-actions">
                <el-dropdown trigger="click" @command="handleCommand">
                  <el-button type="info" text>
                    <el-icon><more /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="viewProfile">查看资料</el-dropdown-item>
                      <el-dropdown-item command="clearHistory">清空聊天记录</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <span style="color: #f56c6c">删除好友</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>

            <!-- 消息列表 -->
            <div ref="messageListRef" class="message-list">
              <div v-if="loading" class="loading-container">
                <el-skeleton :rows="3" animated />
              </div>

              <el-empty v-else-if="messages.length === 0" description="暂无消息记录" />

              <template v-else>
                <div v-for="(message, index) in messages" :key="message.id" class="message-item">
                  <!-- 日期分隔线 -->
                  <div v-if="shouldShowDateDivider(message, index)" class="date-divider">
                    <span>{{ formatDateDivider(message.createdAt) }}</span>
                  </div>

                  <!-- 消息气泡 -->
                  <div
                    class="message-bubble"
                    :class="{
                      'message-sent': message.senderId === userId,
                      'message-received': message.senderId !== userId,
                    }"
                  >
                    <el-avatar
                      v-if="message.senderId !== userId"
                      :size="36"
                      :src="message.senderAvatar || currentFriend.avatar"
                      class="sender-avatar"
                    />

                    <div class="message-content">
                      <div
                        class="message-text"
                        :class="{
                          'sent-text': message.senderId === userId,
                          'received-text': message.senderId !== userId,
                          'image-message': message.type === 'image',
                          'file-message': message.type === 'file',
                        }"
                      >
                        <!-- 文本消息 -->
                        <span v-if="message.type === 'text'">{{ message.content }}</span>

                        <!-- 图片消息 -->
                        <div v-else-if="message.type === 'image'">
                          <el-image
                            :src="message.fileUrl || ''"
                            :preview-src-list="message.fileUrl ? [message.fileUrl] : []"
                            fit="cover"
                            class="message-image"
                          />
                        </div>

                        <!-- 文件消息 -->
                        <div v-else-if="message.type === 'file'" class="file-container">
                          <el-icon><document /></el-icon>
                          <span class="file-name">{{ message.fileName }}</span>
                          <span class="file-size">{{ formatFileSize(message.fileSize) }}</span>
                          <el-button
                            type="primary"
                            size="small"
                            text
                            @click="downloadFile(message)"
                          >
                            下载
                          </el-button>
                        </div>

                        <!-- 表情消息 -->
                        <div v-else-if="message.type === 'emoji'" class="emoji-container">
                          <span class="emoji">{{ message.content }}</span>
                        </div>
                      </div>

                      <div class="message-time">
                        {{ formatMessageTime(message.createdAt) }}
                        <el-icon
                          v-if="message.senderId === userId"
                          :class="['message-status', message.status]"
                          :title="messageStatusText[message.status]"
                        >
                          <check v-if="message.status === 'sent'" />
                          <success-filled v-else-if="message.status === 'delivered'" />
                          <circle-check-filled v-else-if="message.status === 'read'" />
                        </el-icon>
                      </div>
                    </div>

                    <el-avatar
                      v-if="message.senderId === userId"
                      :size="36"
                      :src="userAvatar"
                      class="sender-avatar"
                    />
                  </div>
                </div>

                <div ref="messageEnd"></div>
              </template>
            </div>

            <!-- 输入区域 -->
            <div class="message-input-container">
              <div class="message-toolbar">
                <el-button-group>
                  <el-button icon="picture" @click="openImageUpload"></el-button>
                  <el-button icon="upload" @click="openFileUpload"></el-button>
                  <el-button icon="emoji" @click="openEmojiPicker"></el-button>
                </el-button-group>
              </div>

              <div class="input-area">
                <el-input
                  v-model="messageText"
                  type="textarea"
                  :rows="3"
                  resize="none"
                  placeholder="输入消息..."
                  @keydown.enter.prevent="sendMessage"
                ></el-input>
              </div>

              <div class="send-button">
                <el-button type="primary" :disabled="!messageText.trim()" @click="sendMessage">
                  发送
                </el-button>
              </div>
            </div>

            <!-- 隐藏的文件上传输入 -->
            <input
              ref="fileInputRef"
              type="file"
              style="display: none"
              @change="handleFileSelected"
            />
            <input
              ref="imageInputRef"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleImageSelected"
            />
          </template>
        </div>
      </div>
    </el-card>

    <!-- 添加好友对话框 -->
    <el-dialog v-model="addFriendDialogVisible" title="添加好友" width="500px">
      <el-form
        ref="addFriendFormRef"
        :model="addFriendForm"
        :rules="addFriendRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFriendForm.username" placeholder="请输入用户名、ID或邮箱" />
        </el-form-item>
        <el-form-item label="验证消息" prop="message">
          <el-input
            v-model="addFriendForm.message"
            type="textarea"
            :rows="3"
            placeholder="请输入验证消息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFriendDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddFriend">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 好友请求对话框 -->
    <el-dialog v-model="friendRequestsDialogVisible" title="好友请求" width="650px">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="收到的请求" name="received">
          <el-empty v-if="receivedRequests.length === 0" description="暂无收到的好友请求" />
          <div v-else class="request-list">
            <el-card
              v-for="request in receivedRequests"
              :key="request.id"
              class="request-card"
              shadow="hover"
            >
              <div class="request-info">
                <el-avatar :size="50" :src="request.senderAvatar">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                </el-avatar>
                <div class="request-details">
                  <div class="request-name">{{ request.senderName }}</div>
                  <div class="request-time">{{ formatTime(request.createdAt) }}</div>
                  <div class="request-message">
                    <el-tooltip :content="request.message" placement="top" :hide-after="2000">
                      <span>{{ truncateMessage(request.message) }}</span>
                    </el-tooltip>
                  </div>
                </div>
              </div>
              <div class="request-actions">
                <el-button type="primary" @click="acceptRequest(request)">接受</el-button>
                <el-button type="danger" @click="rejectRequest(request)">拒绝</el-button>
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="发出的请求" name="sent">
          <el-empty v-if="sentRequests.length === 0" description="暂无发出的好友请求" />
          <div v-else class="request-list">
            <el-card
              v-for="request in sentRequests"
              :key="request.id"
              class="request-card"
              shadow="hover"
            >
              <div class="request-info">
                <el-avatar :size="50" :src="request.receiverAvatar">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                </el-avatar>
                <div class="request-details">
                  <div class="request-name">{{ request.receiverName }}</div>
                  <div class="request-time">{{ formatTime(request.createdAt) }}</div>
                  <div class="request-status">
                    <el-tag :type="getStatusType(request.status)" size="small">
                      {{ getStatusText(request.status) }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <div class="request-actions">
                <el-button
                  v-if="request.status === 'pending'"
                  type="danger"
                  @click="cancelRequest(request)"
                >
                  取消请求
                </el-button>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 表情选择器弹窗 -->
    <el-dialog v-model="emojiPickerVisible" title="选择表情" width="400px" align-center>
      <div class="emoji-picker">
        <div v-for="emoji in emojiList" :key="emoji" class="emoji-item" @click="insertEmoji(emoji)">
          {{ emoji }}
        </div>
      </div>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除好友" width="400px">
      <span>确定要删除好友 "{{ currentFriend?.nickname || currentFriend?.username }}" 吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 清空聊天记录对话框 -->
    <el-dialog v-model="clearHistoryDialogVisible" title="清空聊天记录" width="400px">
      <span>
        确定要清空与 "{{ currentFriend?.nickname || currentFriend?.username }}"
        的聊天记录吗？此操作不可恢复。
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearHistoryDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmClearHistory">确认清空</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Check,
  SuccessFilled,
  CircleCheckFilled,
  Document,
  Picture,
  Upload,
  ChatDotRound as Emoji,
  More,
} from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type { FriendInfo, MessageInfo, FriendRequestInfo } from "@/types/social";

const router = useRouter();
const userId = ref(1); // 假设用户ID为1，实际应该从用户状态中获取
const userAvatar = ref("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"); // 用户头像

// 好友列表模拟数据
const friendList = ref<FriendInfo[]>([
  {
    id: 1,
    userId: 101,
    username: "zhang_san",
    nickname: "张三",
    avatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    status: "online",
    unreadCount: 3,
    lastOnlineTime: "",
    online: true,
  },
  {
    id: 2,
    userId: 102,
    username: "li_si",
    nickname: "李四",
    avatar: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
    status: "busy",
    unreadCount: 0,
    lastOnlineTime: "",
    online: true,
  },
  {
    id: 3,
    userId: 103,
    username: "wang_wu",
    nickname: "王五",
    avatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    status: "offline",
    unreadCount: 0,
    lastOnlineTime: "2023-05-20T15:30:00Z",
    online: false,
  },
  {
    id: 4,
    userId: 104,
    username: "zhao_liu",
    nickname: "赵六",
    avatar: "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg",
    status: "online",
    unreadCount: 8,
    lastOnlineTime: "",
    online: true,
  },
  {
    id: 5,
    userId: 105,
    username: "sun_qi",
    nickname: "孙七",
    avatar: "https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png",
    status: "offline",
    unreadCount: 0,
    lastOnlineTime: "2023-05-21T09:15:00Z",
    online: false,
  },
]);

// 搜索和过滤
const searchText = ref("");
const filteredFriends = computed(() => {
  if (!searchText.value) return friendList.value;
  const search = searchText.value.toLowerCase();
  return friendList.value.filter(
    (friend) =>
      friend.username.toLowerCase().includes(search) ||
      (friend.nickname && friend.nickname.toLowerCase().includes(search))
  );
});

// 当前选中的好友
const currentFriendId = ref<number | null>(null);
const currentFriend = ref<FriendInfo | null>(null);

// 消息列表
const messages = ref<MessageInfo[]>([
  {
    id: 1,
    senderId: 1,
    senderName: "我",
    senderAvatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    receiverId: 1,
    content: "你好，最近在忙什么？",
    type: "text",
    status: "read",
    createdAt: "2023-05-21T09:00:00Z",
  },
  {
    id: 2,
    senderId: 101,
    senderName: "张三",
    senderAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    receiverId: 1,
    content: "我在学习Vue3，你呢？",
    type: "text",
    status: "read",
    createdAt: "2023-05-21T09:05:00Z",
  },
  {
    id: 3,
    senderId: 1,
    senderName: "我",
    senderAvatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    receiverId: 1,
    content: "我也在学习Vue3，感觉组合式API很强大",
    type: "text",
    status: "read",
    createdAt: "2023-05-21T09:10:00Z",
  },
  {
    id: 4,
    senderId: 101,
    senderName: "张三",
    senderAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    receiverId: 1,
    content: "确实，比选项式API更灵活",
    type: "text",
    status: "read",
    createdAt: "2023-05-21T09:15:00Z",
  },
  {
    id: 5,
    senderId: 101,
    senderName: "张三",
    senderAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    receiverId: 1,
    content: "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg",
    type: "image",
    status: "read",
    createdAt: "2023-05-21T09:20:00Z",
    fileUrl: "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg",
  },
]);

// 好友请求
const receivedRequests = ref<FriendRequestInfo[]>([
  {
    id: 1,
    senderId: 201,
    senderName: "刘一",
    senderAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    receiverId: 1,
    status: "pending",
    createdAt: "2023-05-21T08:00:00Z",
    message: "我是刘一，请加我为好友",
  },
  {
    id: 2,
    senderId: 202,
    senderName: "陈二",
    senderAvatar: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
    receiverId: 1,
    status: "pending",
    createdAt: "2023-05-22T10:30:00Z",
    message: "我们在同一个群里，加个好友吧",
  },
]);

const sentRequests = ref<FriendRequestInfo[]>([
  {
    id: 3,
    senderId: 1,
    senderName: "我",
    senderAvatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    receiverId: 301,
    receiverName: "周八",
    receiverAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    status: "pending",
    createdAt: "2023-05-22T09:45:00Z",
    message: "我是你的同学，请通过我的好友申请",
  },
]);

// 界面状态
const loading = ref(false);
const messageText = ref("");
const requestCount = ref(2);
const messageListRef = ref<HTMLElement | null>(null);
const messageEnd = ref<HTMLElement | null>(null);

// 对话框控制
const addFriendDialogVisible = ref(false);
const friendRequestsDialogVisible = ref(false);
const emojiPickerVisible = ref(false);
const deleteDialogVisible = ref(false);
const clearHistoryDialogVisible = ref(false);
const activeTab = ref("received");

// 表单相关
const addFriendFormRef = ref<FormInstance>();
const addFriendForm = ref({
  username: "",
  message: "我是你的好友，请通过我的好友申请~",
});

const addFriendRules = ref<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  message: [
    { required: true, message: "请输入验证消息", trigger: "blur" },
    { max: 100, message: "最多100个字符", trigger: "blur" },
  ],
});

// 消息状态文本
const messageStatusText = {
  sent: "已发送",
  delivered: "已送达",
  read: "已读",
};

// 表情列表
const emojiList = ref([
  "😊",
  "😂",
  "🤣",
  "❤️",
  "👍",
  "👏",
  "🙏",
  "🤔",
  "😍",
  "😘",
  "😭",
  "😎",
  "🙄",
  "😒",
  "😢",
  "🤩",
  "😁",
  "😉",
  "��",
  "😱",
]);

// 状态文本
const statusText = {
  online: "在线",
  offline: "离线",
  busy: "忙碌",
};

// 加载好友列表 - 使用模拟数据
const loadFriendList = async () => {
  // 模拟数据已设置，无需加载
  return Promise.resolve();
};

// 获取好友请求数量 - 使用模拟数据
const loadRequestCount = async () => {
  // 使用模拟的固定值
  requestCount.value = receivedRequests.value.length;
  return Promise.resolve();
};

// 加载聊天记录 - 使用模拟数据
const loadMessages = async () => {
  if (!currentFriendId.value) return;

  loading.value = true;
  try {
    // 模拟API调用延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 根据当前好友过滤消息
    if (currentFriendId.value === 1) {
      // 使用默认消息列表，不用过滤
    } else {
      messages.value = []; // 其他好友暂无消息
    }

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error("获取聊天记录失败:", error);
    ElMessage.error("获取聊天记录失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 选择好友
const selectFriend = (friend: FriendInfo) => {
  currentFriendId.value = friend.id;
  currentFriend.value = friend;
  loadMessages();
};

// 发送消息
const sendMessage = () => {
  if (!messageText.value.trim() || !currentFriend.value) return;

  try {
    // 模拟发送消息
    const newMessage: MessageInfo = {
      id: Date.now(),
      senderId: userId.value,
      senderName: "我",
      senderAvatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      receiverId: currentFriend.value.id,
      content: messageText.value,
      type: "text",
      status: "sent",
      createdAt: new Date().toISOString(),
    };

    messages.value.push(newMessage);
    messageText.value = "";

    // 模拟消息状态变化
    setTimeout(() => {
      const index = messages.value.findIndex((m) => m.id === newMessage.id);
      if (index !== -1) {
        messages.value[index].status = "delivered";
      }
    }, 1000);

    setTimeout(() => {
      const index = messages.value.findIndex((m) => m.id === newMessage.id);
      if (index !== -1) {
        messages.value[index].status = "read";
      }
    }, 2000);

    // 滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
  } catch (error) {
    console.error("发送消息失败:", error);
    ElMessage.error("发送消息失败，请稍后重试");
  }
};

// 打开添加好友对话框
const openAddFriendDialog = () => {
  addFriendDialogVisible.value = true;
  addFriendForm.value = {
    username: "",
    message: "我是你的好友，请通过我的好友申请~",
  };
};

// 打开好友请求对话框
const openFriendRequests = () => {
  friendRequestsDialogVisible.value = true;
  activeTab.value = "received";
};

// 提交添加好友
const submitAddFriend = async () => {
  if (!addFriendFormRef.value) return;

  await addFriendFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 模拟添加好友成功
        ElMessage.success("好友请求已发送");
        addFriendDialogVisible.value = false;

        // 添加到已发送请求列表
        sentRequests.value.push({
          id: Date.now(),
          senderId: userId.value,
          senderName: "我",
          senderAvatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
          receiverId: 999, // 模拟接收者ID
          status: "pending",
          createdAt: new Date().toISOString(),
          message: addFriendForm.value.message,
        });
      } catch (error) {
        console.error("发送好友请求失败:", error);
        ElMessage.error("发送好友请求失败，请稍后重试");
      }
    }
  });
};

// 接受好友请求
const acceptRequest = async (request: FriendRequestInfo) => {
  try {
    // 模拟接受请求
    const index = receivedRequests.value.findIndex((r) => r.id === request.id);
    if (index !== -1) {
      receivedRequests.value[index].status = "accepted";

      // 添加到好友列表
      friendList.value.push({
        id: friendList.value.length + 10,
        userId: request.senderId,
        username: request.senderName.toLowerCase().replace(" ", "_"),
        nickname: request.senderName,
        avatar: request.senderAvatar,
        status: "online",
        unreadCount: 0,
        lastOnlineTime: "",
        online: true,
      });

      ElMessage.success("已接受好友请求");
      requestCount.value = receivedRequests.value.filter((r) => r.status === "pending").length;
    }
  } catch (error) {
    console.error("接受好友请求失败:", error);
    ElMessage.error("接受好友请求失败，请稍后重试");
  }
};

// 拒绝好友请求
const rejectRequest = async (request: FriendRequestInfo) => {
  try {
    // 模拟拒绝请求
    const index = receivedRequests.value.findIndex((r) => r.id === request.id);
    if (index !== -1) {
      receivedRequests.value[index].status = "rejected";
      ElMessage.success("已拒绝好友请求");
      requestCount.value = receivedRequests.value.filter((r) => r.status === "pending").length;
    }
  } catch (error) {
    console.error("拒绝好友请求失败:", error);
    ElMessage.error("拒绝好友请求失败，请稍后重试");
  }
};

// 取消好友请求
const cancelRequest = async (_request: FriendRequestInfo) => {
  try {
    // 模拟取消请求
    const index = sentRequests.value.findIndex((r) => r.id === _request.id);
    if (index !== -1) {
      sentRequests.value.splice(index, 1);
      ElMessage.success("已取消好友请求");
    }
  } catch (error) {
    console.error("取消好友请求失败:", error);
    ElMessage.error("取消好友请求失败，请稍后重试");
  }
};

// 插入表情
const insertEmoji = (emoji: string) => {
  messageText.value += emoji;
  emojiPickerVisible.value = false;
};

// 删除好友
const confirmDeleteFriend = async () => {
  if (!currentFriend.value) return;

  try {
    // 模拟删除好友
    const index = friendList.value.findIndex((f) => f.id === currentFriend.value!.id);
    if (index !== -1) {
      friendList.value.splice(index, 1);
    }

    ElMessage.success("删除成功");
    deleteDialogVisible.value = false;
    currentFriend.value = null;
    currentFriendId.value = null;
  } catch (error) {
    console.error("删除好友失败:", error);
    ElMessage.error("删除好友失败，请稍后重试");
  }
};

// 准备删除好友
const prepareFriendDelete = (friend: FriendInfo) => {
  currentFriend.value = friend;
  deleteDialogVisible.value = true;
};

// 滚动到底部
const scrollToBottom = () => {
  if (messageEnd.value) {
    messageEnd.value.scrollIntoView({ behavior: "smooth" });
  }
};

// 获取好友最后一条消息
const getLastMessage = (_friend: FriendInfo) => {
  // 实际情况中，这个信息应该从好友对象中获取
  return "暂无消息";
};

// 获取好友最后一条消息时间
const getLastMessageTime = (_friend: FriendInfo) => {
  // 实际情况中，这个信息应该从好友对象中获取
  return "";
};

// 判断是否显示日期分隔线
const shouldShowDateDivider = (message: MessageInfo, index: number) => {
  if (index === 0) return true;

  const prevMessage = messages.value[index - 1];
  const prevDate = new Date(prevMessage.createdAt).toLocaleDateString();
  const currentDate = new Date(message.createdAt).toLocaleDateString();

  return prevDate !== currentDate;
};

// 格式化日期分隔线
const formatDateDivider = (dateString: string) => {
  const date = new Date(dateString);
  const now = new Date();
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);

  if (date.toLocaleDateString() === now.toLocaleDateString()) {
    return "今天";
  } else if (date.toLocaleDateString() === yesterday.toLocaleDateString()) {
    return "昨天";
  } else {
    return date.toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" });
  }
};

// 格式化消息时间
const formatMessageTime = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
};

// 格式化文件大小
const formatFileSize = (bytes?: number) => {
  if (!bytes) return "未知大小";

  const units = ["B", "KB", "MB", "GB", "TB"];
  let size = bytes;
  let unitIndex = 0;

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  return `${size.toFixed(2)} ${units[unitIndex]}`;
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return "";
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1天
  if (diff < 86400000) {
    return date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
  }
  // 小于7天
  else if (diff < 604800000) {
    const days = ["日", "一", "二", "三", "四", "五", "六"];
    return `周${days[date.getDay()]} ${date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" })}`;
  }
  // 大于7天
  else {
    return date.toLocaleDateString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  }
};

// 获取状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case "pending":
      return "info";
    case "accepted":
      return "success";
    case "rejected":
      return "danger";
    default:
      return "info";
  }
};

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case "pending":
      return "等待处理";
    case "accepted":
      return "已接受";
    case "rejected":
      return "已拒绝";
    default:
      return "未知状态";
  }
};

// 下载文件
const downloadFile = (message: MessageInfo) => {
  if (!message.fileUrl) {
    ElMessage.error("文件下载链接不存在");
    return;
  }

  window.open(message.fileUrl, "_blank");
};

// 截断消息内容
const truncateMessage = (message: string) => {
  if (!message) return "";
  return message.length > 20 ? message.substring(0, 20) + "..." : message;
};

// 处理下拉菜单命令
const handleCommand = (command: string) => {
  if (!currentFriend.value) return;

  switch (command) {
    case "viewProfile":
      router.push(`/userinfo/index/${currentFriend.value.userId}`);
      break;
    case "delete":
      deleteDialogVisible.value = true;
      break;
    case "clearHistory":
      clearHistoryDialogVisible.value = true;
      break;
  }
};

// 确认删除好友
const confirmDelete = async () => {
  await confirmDeleteFriend();
};

// 确认清空聊天记录
const confirmClearHistory = async () => {
  if (!currentFriend.value) return;

  // 实际应该调用清空聊天记录API
  try {
    // await clearChatHistory(currentFriend.value.id);
    ElMessage.success("聊天记录已清空");
    clearHistoryDialogVisible.value = false;

    // 清空消息列表
    messages.value = [];
  } catch (error) {
    console.error("清空聊天记录失败:", error);
    ElMessage.error("清空聊天记录失败，请稍后重试");
  }
};

// 监听路由和localStorage数据
onMounted(async () => {
  await loadFriendList();
  await loadRequestCount();

  // 检查是否需要打开好友请求对话框
  const shouldOpenRequests = localStorage.getItem("openFriendRequests");
  if (shouldOpenRequests === "true") {
    localStorage.removeItem("openFriendRequests");
    openFriendRequests();
  }

  // 检查是否有指定的好友ID需要选中
  const selectedFriendId = localStorage.getItem("selectedFriendId");
  if (selectedFriendId && friendList.value.length > 0) {
    const targetFriend = friendList.value.find((f) => f.id === Number(selectedFriendId));
    if (targetFriend) {
      selectFriend(targetFriend);
    }
    localStorage.removeItem("selectedFriendId");
  }
});
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.social-container {
  display: flex;
  height: 700px;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 10px;
}

// 好友侧边栏
.friends-sidebar {
  width: 280px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  .search-input {
    padding: 10px;
    border-bottom: 1px solid #e4e7ed;
  }

  .friend-list {
    flex: 1;
    overflow-y: auto;

    .friend-item {
      display: flex;
      padding: 10px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      &.active {
        background-color: #ecf5ff;
      }

      .friend-avatar {
        position: relative;
        margin-right: 10px;

        .status-dot {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 10px;
          height: 10px;
          border-radius: 50%;
          border: 2px solid #fff;

          &.online {
            background-color: #67c23a;
          }

          &.offline {
            background-color: #909399;
          }

          &.busy {
            background-color: #e6a23c;
          }
        }
      }

      .friend-info {
        flex: 1;
        min-width: 0;

        .friend-name {
          font-size: 14px;
          font-weight: bold;
          margin-bottom: 3px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .last-message {
          font-size: 12px;
          color: #909399;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .friend-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        justify-content: space-between;
        min-width: 50px;

        .message-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

// 聊天内容区
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;

  .empty-chat {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .chat-header {
    padding: 10px 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e4e7ed;
    background-color: #fff;

    .friend-info {
      display: flex;
      flex-direction: column;

      .friend-name {
        font-size: 16px;
        font-weight: bold;
      }

      .friend-status {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .message-list {
    flex: 1;
    overflow-y: auto;
    padding: 15px;

    .loading-container {
      padding: 20px;
    }

    .date-divider {
      text-align: center;
      margin: 10px 0;

      span {
        display: inline-block;
        padding: 2px 10px;
        font-size: 12px;
        background-color: #f2f6fc;
        color: #909399;
        border-radius: 10px;
      }
    }

    .message-item {
      margin-bottom: 15px;
    }

    .message-bubble {
      display: flex;
      align-items: flex-start;

      &.message-sent {
        flex-direction: row-reverse;

        .message-content {
          margin-right: 10px;
        }
      }

      &.message-received {
        flex-direction: row;

        .message-content {
          margin-left: 10px;
        }
      }

      .message-content {
        max-width: 70%;

        .message-text {
          padding: 10px;
          border-radius: 8px;
          margin-bottom: 5px;

          &.sent-text {
            background-color: #95d475;
            color: #fff;
          }

          &.received-text {
            background-color: #fff;
            color: #303133;
          }

          &.image-message {
            padding: 0;
            overflow: hidden;

            .message-image {
              max-width: 200px;
              max-height: 200px;
              border-radius: 8px;
            }
          }

          &.file-message {
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            .file-name {
              font-weight: bold;
              margin: 0 10px;
              flex: 1;
              word-break: break-all;
            }

            .file-size {
              font-size: 12px;
              color: #909399;
              margin-right: 10px;
            }
          }
        }

        .message-time {
          font-size: 12px;
          color: #909399;
          text-align: right;
          display: flex;
          justify-content: flex-end;
          align-items: center;

          .message-status {
            margin-left: 5px;
            font-size: 14px;

            &.sent {
              color: #909399;
            }

            &.delivered {
              color: #409eff;
            }

            &.read {
              color: #67c23a;
            }
          }
        }
      }
    }
  }

  .message-input-container {
    padding: 10px;
    background-color: #fff;
    border-top: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;

    .message-toolbar {
      padding: 5px 0;
      margin-bottom: 5px;
    }

    .input-area {
      flex: 1;
      margin-bottom: 10px;
    }

    .send-button {
      display: flex;
      justify-content: flex-end;
    }
  }
}

// 好友请求样式
.request-list {
  margin-top: 20px;
}

.request-card {
  margin-bottom: 15px;

  .request-info {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;

    .el-avatar {
      margin-right: 15px;
    }

    .request-details {
      flex: 1;

      .request-name {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 4px;
      }

      .request-time {
        font-size: 12px;
        color: #909399;
        margin-bottom: 8px;
      }

      .request-message,
      .request-status {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .request-actions {
    display: flex;
    justify-content: flex-end;

    .el-button {
      margin-left: 10px;
    }
  }
}

// 表情选择器样式
.emoji-picker {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  max-height: 300px;
  overflow-y: auto;

  .emoji-item {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    cursor: pointer;
    transition: all 0.2s;
    border-radius: 4px;

    &:hover {
      background-color: #f5f7fa;
    }
  }
}
</style>
